package com.mf.controller;

import com.mf.entity.bo.BasicSocketBo;
import com.mf.service.IBasicSocketService;
import com.mf.service.dto.WebSocketDto;
import com.mf.service.impl.WebSocketServiceImpl;
import io.github.heollhai.common.entity.request.SocketMessageRequest;
import io.github.heollhai.common.result.Result;
import io.github.heollhai.common.utils.VerifyUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: lmf
 * @Create: 2024/10/17 9:12
 * Description:
 */
@RestController
@RequestMapping("/basic/socket/v1")
@Tag(name = "websocket-通讯")
@Slf4j
public class WebSocketController {
    @Resource
    private IBasicSocketService basicSocketService;

    @PostMapping("/send")
    @Operation(summary = "RPC-发送消息-广播消息给所有会话")
    public Result<String> send(@Valid @RequestBody() SocketMessageRequest socketMessageRequest) {
        log.info("当前消息内容:{}", socketMessageRequest);
        BasicSocketBo basicSocketBo = new BasicSocketBo();
        BeanUtils.copyProperties(socketMessageRequest, basicSocketBo);
//        // 将消息暂时存入数据库, 待消息发送成功后删除
//        basicSocketService.save(basicSocketBo);

        socketMessageRequest.setSocketId(basicSocketBo.getId());
        log.info("当前消息id:{}", socketMessageRequest.getSocketId());
        if (VerifyUtils.isEmpty(socketMessageRequest.getUserId())) {
            WebSocketServiceImpl.sendAllMessage(socketMessageRequest);
        } else {
            WebSocketServiceImpl.sendTextMessageByUserId(socketMessageRequest);
        }
        return Result.success();
    }

    @Operation(summary = "获取socket连接用户列表")
    @GetMapping("findSocketList")
    public Result<List<String>> findSocketList() {
        List<String> ids = new ArrayList<>();
        WebSocketServiceImpl.webSocketByUserIdMap.forEach((k, v) -> {
            for (WebSocketDto webSocketDto : v) {
                ids.add("sid=>"+webSocketDto.getSessionId()+"uid=>"+webSocketDto.getUserId());
            }
        });

        return Result.success(ids);
    }

}
